package lagou.work3;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * 服务器类
 */
public class Server {
    private static ServerSocket serverSocket = null;
    private static Socket socket = null;
    /**
     * 定义一个类型为socket的list，每当有新的客户端连接后，就启动服务器聊天线程
     */
    private static List<Socket> list = new ArrayList<>();


    public static void main(String[] args) {
        connect();
    }

    /**
     * 等待客户端连接，连接后开启服务器线程
     */
    public static void connect() {
        try {
            serverSocket = new ServerSocket(9999);
            while (true) {
                System.out.println("等待客户端的连接请求");
                socket = serverSocket.accept();
                list.add(socket);
                System.out.println("客户端" + socket.getInetAddress() + "连接成功");
                new ServerThread(list,socket).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != serverSocket) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
